package com.ruoyi.system.controller;

import java.util.HashMap;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.http.HttpUtils;

public class CorpWechatAppHelper {
	
	/**
	 * 存储获取的 Access Token
	 */
	private String accessToken;
	
	/**
	 * 过期时间：
	 */
	private long expiresOut;
	
	// 企业微信唯一标识（不可变）
	private String corpid;
	// 企业微信内的某个应用的唯一标识（一般不变，除非手动在企业微信后台重置）
	private String corpsecret;
	
    public CorpWechatAppHelper(String corpid, String corpsecret) {
		super();
		this.corpid = corpid;
		this.corpsecret = corpsecret;
	}

	protected synchronized String getAccessToken() {
		if((System.currentTimeMillis() / 1000) > expiresOut) {
	    	String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken";
	    	String param = String.format("corpid=%s&corpsecret=%s", corpid, corpsecret);
	    	
	    	String response = HttpUtils.sendGet(url, param);
	    	JSONObject json = JSONObject.parseObject(response);
	    	
	    	if(json.getInteger("errcode") == 0) {
		    	accessToken = json.getString("access_token");
		    	expiresOut = (System.currentTimeMillis() / 1000) + json.getLongValue("expires_in");
	    	}
		}else {
			return accessToken;
		}
		
    	return accessToken;
    }
	
	/*
		 {
		   "errcode": 0,
		   "errmsg": "ok",
		   "UserId":"USERID",
		   "DeviceId":"DEVICEID"
		}
	 */
    public String getUserId(String code) {
    	String accessToken = getAccessToken();
    	String url = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo";
    	String param = String.format("access_token=%s&code=%s", accessToken, code);
    	
    	String response = HttpUtils.sendGet(url, param);
    	JSONObject json = JSONObject.parseObject(response);
    	
    	if(json.getInteger("errcode") == 0) {
    		String userId = json.getString("UserId");
    		return userId;
    	}
    	
    	// return "errorcode : " + json.getInteger("errcode");
    	return "ry";
    }
}